package com.c.ctgproject.ui.sell.material

import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.c.ctgproject.R
import com.c.ctgproject.adapter.MaterialDetailListAdapter
import com.c.ctgproject.base.BaseActivity
import com.c.ctgproject.entity.MaterialDetailEntity
import com.c.ctgproject.utils.*
import kotlinx.android.synthetic.main.activity_material_sell_detail.*
import java.util.ArrayList

/**
 *作者:LiBW
 *创建日期: 2020/9/8
 *描述: 物料详情页
 */
class MaterialDetailActivity : BaseActivity() {
    private val mViewModel: MaterialDetailViewModel by lazy { ViewModelProvider(this)[MaterialDetailViewModel::class.java] }
    private val mList = ArrayList<MaterialDetailEntity.DataBean.ListBean>()
    private val mAdapter: MaterialDetailListAdapter by lazy { MaterialDetailListAdapter(this, mList) }
    private var page = 1
    private val size = 5
    override fun getLayout() = R.layout.activity_material_sell_detail
    override fun event() {
        changeTransparentStatusBar()
        changeStatusIconColor(true)
        mMaterialDetailListRV.adapter = mAdapter
        mMaterialDetailListRV.layoutManager = LinearLayoutManager(this)
        //获取详情
        mViewModel.getDetail(page, size)
        //详情回调
        mViewModel.detail.observe(this, Observer {
            MyLog.d("物料详情回调:$it")
            val data = initData(it)
            if (data.status == 0) {
                mRefresh.finishLoadMore()
                mRefresh.finishRefresh()
                val entity = getGson().fromJson(it, MaterialDetailEntity::class.java).data
                entity?.list?.let {list->
                    mList.addAll(list)
                    mAdapter.notifyDataSetChanged()
                }

            } else {
                CustomToast.showToast(this, data.msg.handlerNull())
            }
        })
        //通用错误回调
        mViewModel.error.observe(this, Observer {
            MyLog.d("物料详情页面错误回调:$it")
            CustomToast.showToast(this, it)
        })
    }

    override fun click() {
        //下拉刷新
        mRefresh.setOnRefreshListener {
            //获取详情
            mList.clear()
            page = 1
            mViewModel.getDetail(page, size)
        }
        //上啦加载
        mRefresh.setOnLoadMoreListener {
            //获取详情
            page++
            MyLog.d("当前查询的页数:$page")
            mViewModel.getDetail(page, size)
        }
    }
}